package com.peakmain.baselibrary.db;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.ArrayMap;
import android.util.Log;


import com.peakmain.baselibrary.db.curd.QuerySupport;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * 作者：Peakmain
 * 版本：1.0
 * 创建日期：2018/6/23 0023 上午 10:25
 * 邮件:2726449200@qq.com
 * 描述：
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public class DaoSupport<T> implements IDaoSupport<T> {
    private SQLiteDatabase mSQLiteDatabase;
    private Class<T> mClazz;
    private String TAG = DaoSupport.class.getSimpleName();
    private static final Object[] mPutMethodArgs = new Object[2];

    private static final Map<String, Method> mPutMethods = new ArrayMap<>();
 private QuerySupport mQuerySupport;
    @Override
    public void init(SQLiteDatabase sqLiteDatabase, Class<T> clazz) {
        // 创建表
        /*"create table if not exists Person ("
                + "id integer primary key autoincrement, "
                + "name text, "
                + "age integer, "
                + "flag boolean)";*/
        this.mSQLiteDatabase = sqLiteDatabase;
        this.mClazz = clazz;
        StringBuilder sb = new StringBuilder();
        sb.append("create table if not exists ")
                .append(DaoUtil.getTableName(mClazz))
                .append("(id integer primary key autoincrement, ");
        Field[] fields = mClazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            String type = field.getType().getSimpleName();//int String boolean
            //  type需要进行转换 int --> integer, String text;
            sb.append(name).append(DaoUtil.getColumnType(type)).append(", ");
        }
        sb.replace(sb.length() - 2, sb.length(), ")");
        String createTableSql = sb.toString();
        Log.e(TAG, "创建表的语句->" + createTableSql);
        //创建表
        mSQLiteDatabase.execSQL(createTableSql);
    }

    /**
     * 插入数据库
     */
    @Override
    public long insert(T o) {
          /*ContentValues values = new ContentValues();
        values.put("name",person.getName());
        values.put("age",person.getAge());
        values.put("flag",person.getFlag());
        db.insert("Person",null,values);*/
        ContentValues values = ContentValuesByObj(o);
        return mSQLiteDatabase.insert(DaoUtil.getTableName(mClazz), null, values);
    }

    @Override
    public void insert(List<T> datas) {
        //批量插入,开启事务
        mSQLiteDatabase.beginTransaction();
        for (T data : datas) {
            //调用单条插入
            insert(data);
        }
        //结束事务
        mSQLiteDatabase.setTransactionSuccessful();
        mSQLiteDatabase.endTransaction();
    }

    @Override
    public QuerySupport<T> querySupport() {
        if(mQuerySupport==null){
            mQuerySupport=new QuerySupport(mSQLiteDatabase,mClazz);

        }
        return mQuerySupport;
    }


    /**
     * 删除
     */
    @Override
    public int delete(String whereClause, String[] whereArgs) {
        return mSQLiteDatabase.delete(DaoUtil.getTableName(mClazz), whereClause, whereArgs);
    }

    /**
     * 更新
     */
    @Override
    public int update(T obj, String whereClause, String... whereArgs) {
        ContentValues values = ContentValuesByObj(obj);
        return mSQLiteDatabase.update(DaoUtil.getTableName(mClazz), values, whereClause, whereArgs);
    }



    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private ContentValues ContentValuesByObj(T o) {
           /*ContentValues values = new ContentValues();
        values.put("name",person.getName());
        values.put("age",person.getAge());
        values.put("flag",person.getFlag());
        db.insert("Person",null,values);*/
        ContentValues values = new ContentValues();
        //封装values
        //获得class中所有的属性
        Field[] fields = mClazz.getDeclaredFields();

        for (Field field : fields) {
            try {
                // 设置权限，私有和共有都可以访问
                field.setAccessible(true);
                String key = field.getName();
                Object value = field.get(o);
                //参考
                mPutMethodArgs[0] = key;
                mPutMethodArgs[1] = value;
                //第二个是参数类型，把它转换
               /* if(value instanceof Integer){
                    values.put(key, (Integer) value);
                }*/
                //获取ContentValues中的put方法
                //第一个参数key为String类型
                //缓存方法
                String name = field.getType().getName();
                Method putMethod = mPutMethods.get(name);
                if (putMethod == null) {
                    putMethod = ContentValues.class.getDeclaredMethod("put", String.class, value.getClass());
                    mPutMethods.put(name, putMethod);
                }
                //通过反射执行
                putMethod.invoke(values, mPutMethodArgs);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mPutMethodArgs[0] = null;
                mPutMethodArgs[1] = null;
            }
        }
        return values;
    }
    // 查询


    // 修改


    // 删除
}
